﻿using CRM.Infrastructure.Attr;
using CRM.Infrastructure.Dto.Response;
using CRM.Infrastructure.EFCore.Mysql;
using Crm.Service.Instance;
using CRM.Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CRM.Infrastructure.Dto.Request.order;
using CRM.Infrastructure.IOC;
using Microsoft.EntityFrameworkCore;
using CRM.Infrastructure.Tools;
using CRM.Infrastructure.Dto.Response.PC;
using CRM.Infrastructure.Dto.Response.Room;
using MySqlX.XDevAPI.Common;
using System.Xml.Linq;

namespace CRM.Service.Instance
{
    [Inject_]
    public class Order_Service : Base_Service, I_Order_Service
    {
        private readonly Order_IOC _order_IOC;
        private readonly Products_IOC _products_IOC;
        public Order_Service(Order_IOC order_IOC, Products_IOC products_IOC)
        {
            _order_IOC = order_IOC;
            _products_IOC = products_IOC;
        }

        /// <summary>
        /// 完成支付
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="money"></param>
        /// <returns></returns>
        public Api_Response_Dto Finish_Pay(string pid, string money)
        {
            var pay = _order_IOC._order_Pay_EFCore.QueryAll(d => d.Pid == pid).SingleOrDefault();
            if (pay == null)
            {
                return Result(0, "订单不存在");
            }
            if (pay.PIsFinish == 1)
            {
                return Result(0, "订单已支付");
            }
            decimal pmoney = Convert.ToDecimal(money);
            if (pay.PMoney != pmoney)
            {
                return Result(0, "支付金额异常");
            }
            pay.PFinishTime = DateTime.Now;
            pay.PIsFinish = 1;

            var order = _order_IOC._order_EFCore.QueryAll(d => d.OId == pay.PoId).SingleOrDefault();
            if (order == null)
            {
                return Result(0, "订单不存在");
            }
            if (order.OIsFinish == 1)
            {
                return Result(0, "订单已支付");
            }
            order.OPayModel = 1;
            order.OMoney = pmoney;
            order.OPayTime = DateTime.Now;
            order.OIsFinish = 1;

            _order_IOC._order_Pay_EFCore.Update(pay);
            _order_IOC._order_EFCore.Update(order);
            var result = _order_IOC._order_Pay_EFCore.Transactions(_order_IOC._order_EFCore);
            return Result(result ? 1 : 0);


        }


        /// <summary>
        /// 生成订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Generate_Order(Order_Request_Dto dto)
        {
            //如果房间号是唯一的，那么同一个房间在同一时间段 是不能够被多次使用的

            var iq = _order_IOC._order_EFCore.QueryAll(d => d.ORoom == dto.room && d.OIsFinish == 0);
            if (await iq.AnyAsync())
            {
                return Result(0, "房间当前正在使用");
            }


            Order order = new Order()
            {
                OId = RandomNumber.GeneraOrderNumber(),
                ODateTime = DateTime.Now,
                OPeople = dto.people,
                ORoom = dto.room,
                OIsFinish = 0,
                OPayment = 0,
                OMoney = 0,
                OPayMoney = 0
            };
            _order_IOC._order_EFCore.Add(order);
            var result = await _order_IOC._order_EFCore.SaveChangesAsync();
            return Result(result);
        }

        /// <summary>
        /// 生成支付订单
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="oid"></param>
        /// <param name="money"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Generate_Pay(string pid, string? oid, decimal? money)
        {
            var order = await _order_IOC._order_EFCore.QueryAll(d => d.OId == oid).SingleOrDefaultAsync();
            if (order == null)
            {
                return Result(0, "订单不存在");
            }
            if (order.OIsFinish == 1)
            {
                return Result(0, "订单已完成支付");
            }

            OrderPay orderPay = new OrderPay()
            {
                Pid = pid,
                PoId = order.OId,
                PMoney = money,
                PCreateTime = DateTime.Now,
                PIsFinish = 0,
            };
            _order_IOC._order_Pay_EFCore.Add(orderPay);
            var result = await _order_IOC._order_Pay_EFCore.SaveChangesAsync();

            return Result(result);

        }

        /// <summary>
        /// 获取当前房间的订单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Get_Order_By_Room(string id)
        {
            var data = await _order_IOC._order_EFCore.QueryAll(d => d.ORoom == id && d.OIsFinish == 0)
                 .Select(d => new Room_Order_Response_Dto
                 {
                     id = d.OId,
                     people = d.OPeople,
                     count = 0,
                     customer = "",
                     money = d.OMoney,
                     room = d.ORoom,
                 }).SingleOrDefaultAsync();

            if (data == null)
            {
                return Result(0, "无订单数据");
            }
            var details = await _order_IOC._order_Product_EFCore.QueryAll(d => d.OId == data.id).Select(d => new
             Order_Detail
            {
                id = d.OpId,
                name = d.OpName,
                money = d.OpMoney,
                photo = d.OpPhoto,
                count = d.OpCount,
                p_id = d.PId,
                sum = d.OpCount * d.OpMoney
            }).ToListAsync();
            var name = _products_IOC._products_EFCore.QueryAll();
            details.ForEach(d =>
            {
            for (int i = 0 ; i < d.name.Length; i++){
                    if ((int)d.name[i]>127)
                    {

                    }
                    else
                    {
                        d.name = name.Where(e => e.ProductId == d.name).SingleOrDefault()?.ProductName;
                    }
            }
            });
            data.details = details;


            return Result(1, "ok", data);
        }

        /// <summary>
        /// 更新订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>

        public async Task<Api_Response_Dto> Update_Order(Order_Request_Dto dto)
        {
            var iq = _order_IOC._order_EFCore.QueryAll(d => d.OId == dto.id);
            if (!await iq.AnyAsync())
            {
                return Result(0, "订单不存在");
            }

            var d_iq = _order_IOC._order_Product_EFCore.QueryAll(d => d.OId == dto.id);

            _order_IOC._order_Product_EFCore.DeleteRange(d_iq);
            List<OrderProduct> details = new List<OrderProduct>();
            dto.details!.ForEach(d =>
            {
                details.Add(new OrderProduct()
                {
                    OpId = RandomNumber.GeneraOrderNumber2(),
                    OId = dto.id,
                    OpCount = d.count,
                    ODateTime = DateTime.Now,
                    OpIsPay = 0,
                    OpMoney = d.money,
                    PId = d.id,
                    OpName = d.name,
                    OpPhoto = d.photo,
                    OpSum = d.money * d.count
                });
            });

            _order_IOC._order_Product_EFCore.AddRange(details);
            var order = await iq.SingleAsync();
            order.OMoney = details.Sum(d => d.OpSum);
            order.OCount = details.Sum(d => d.OpCount);
            _order_IOC._order_EFCore.Update(order);
            //分布式事务

            var result = _order_IOC._order_Product_EFCore.Transactions(_order_IOC._order_Product_EFCore);
            return Result(result ? 1 : 0);


        }
        public async Task<Api_Response_Dto> Get_Room()
        {
            var iq = _order_IOC._room_EFCode.QueryAll();
            var data = await iq.Select(d => new Room_Response_Dto
            {
                id = d.RId,
                name = d.RRoom,
                state = d.RState,
                time = d.RDateTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
            }).ToListAsync();
            return Result(1, "ok", new
            {
                data,
            });
        }

        public async Task<Api_Response_Dto> Get_Order()
        {
            var data = await _order_IOC._order_EFCore.QueryAll()
                .Select(d => new Order_Response_Dto
                {
                    id = d.OId,
                    count = d.OCount,
                    money = d.OMoney,
                    room = d.ORoom,
                    finish = d.OIsFinish,
                    payment = d.OPayment,
                    time=d.ODateTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                }).ToListAsync();
            var room=_order_IOC._room_EFCode.QueryAll();
            data.ForEach(d =>
            {
                d.room=room.Where(e=>e.RId==d.room).SingleOrDefault()?.RRoom;
            });
            if (data == null)
            {
                return Result(0, "无订单数据");
            }
            return Result(1, "ok", data);
        }

        public async Task<Api_Response_Dto> Get_Order_details(string id)
        {
            var data = await _order_IOC._order_Product_EFCore.QueryAll(d=>d.OId==id)
                .Select(d => new Order_Response_Dto
                {
                    id = d.OId,
                    count = d.OpCount,
                    money = d.OpMoney,
                    sum=d.OpCount* d.OpMoney,
                    name=d.OpName,
                    img=d.OpPhoto,
                    time = d.ODateTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                }).ToListAsync();
                var name = _products_IOC._products_EFCore.QueryAll();
            data.ForEach(d =>
            {
                for (int i = 0; i < d.name.Length; i++)
                {
                    if ((int)d.name[i] > 127)
                    {

                    }
                    else
                    {
                        d.name = name.Where(e => e.ProductId == d.name).SingleOrDefault()?.ProductName;
                    }
                }
            });
                
            if (data == null)
            {
                return Result(0, "无订单数据");
            }
            return Result(1, "ok", data);
        }
    }
}
